package org.ishequ.service;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.ishequ.utils.FormFile;
import org.ishequ.utils.SocketHttpRequester;

public class NewsService {

	public static boolean save(String name, String timelen,String method) throws Exception {
		String path = "http://192.168.1.215:8080/web/addnews";
		Map<String,String> params = new HashMap<String,String>();
		params.put("name", name);
		params.put("timelen", timelen);
		
		if("GET".equals(method))
			return sendHttpGETRequest(path,params,"UTF-8");
		else if("POST".equals(method))
			return sendHttpPOSTRequest(path,params,"UTF-8");
		else if("HTTPCLIENT_POST".equals(method)) 
			return sendHttpClentPOSTRequest(path,params,"UTF-8");
		return false;
	}
	
	public static boolean saveWithFile(String name, String timelen,FormFile uploadFile) throws Exception {
		String path = "http://192.168.1.215:8080/web/addnews";
		Map<String,String> params = new HashMap<String,String>();
		params.put("name", name);
		params.put("timelen", timelen);
		return sendSocketHttpRequester(path,params,uploadFile);
	}

	/**
	 * GET请求发送
	 * @param path 请求路径
	 * @param params 参数Map
	 * @param encoding 参数编码类型
	 * @return 请求成功标记
	 * @throws Exception
	 */
	private static boolean sendHttpGETRequest(String path,
			Map<String, String> params, String encoding) throws Exception {
		StringBuilder url = new StringBuilder(path);
		url.append("?");
		for(Map.Entry<String, String> param :params.entrySet()){
			url.append(param.getKey()).append("=");
			url.append(URLEncoder.encode(param.getValue(), encoding));
			url.append("&");
		}
		url = url.deleteCharAt(url.length()-1);
		HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString()).openConnection());
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode() == 200)
			return true;
		return false;
	}
	
	/**
	 * POST请求发送
	 * @param path 请求路径
	 * @param params 参数
	 * @param encoding 参数编码
	 * @return 请求成功标记
	 * @throws Exception
	 */
	private static boolean sendHttpPOSTRequest(String path,
			Map<String, String> params, String encoding) throws Exception {
		StringBuilder data = new StringBuilder(path);
		for(Map.Entry<String, String> param :params.entrySet()){
			data.append(param.getKey()).append("=");
			data.append(URLEncoder.encode(param.getValue(), encoding));
			data.append("&");
		}
		data = data.deleteCharAt(data.length()-1);
		byte[] entity = data.toString().getBytes(); //生成实体数据
		HttpURLConnection conn = (HttpURLConnection) (new URL(path).openConnection());
		conn.setReadTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);//允许对外输出数据
		//组拼HTTP协议
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
		OutputStream out = conn.getOutputStream();
		out.write(entity);
		if(conn.getResponseCode() == 200)
			return true;
		return false;
	}
	
	private static boolean sendHttpClentPOSTRequest(String path,
			Map<String, String> params, String encoding) throws Exception {
		
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for(Map.Entry<String, String> entry: params.entrySet()){
			pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,encoding);
		HttpPost httpPost = new HttpPost(path);
		httpPost.setEntity(entity);
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse httpResponse = client.execute(httpPost);
		if(httpResponse.getStatusLine().getStatusCode() == 200)
			return true;
		return false;
	}

	public static boolean sendSocketHttpRequester(String path, Map<String, String> params, FormFile uploadfile) throws Exception {
		return SocketHttpRequester.post(path, params, uploadfile);
	}

}
